using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using DTO;
using System.Configuration;
using System.Data;

namespace DAL
{
    public class LOAIHANG_DAL
    {
        private SqlConnection cn = null;
        public LOAIHANG_DAL()
        {
            cn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConnection"]
                 .ConnectionString);
            cn.Open();
          
        }
        public void insert(LoaiHang_DTO loai)
        {
            SqlCommand cmd = new SqlCommand("LOAIHANG_INSERT", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@TENLOAI", loai.TenLoai);
            cmd.ExecuteNonQuery();
        }
        public void update(LoaiHang_DTO loai)
        {
            SqlCommand cmd = new SqlCommand("LOAIHANG_UPDATE", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@MALOAI", loai.MaLoai);
            cmd.Parameters.AddWithValue("@TENLOAI", loai.TenLoai);
            cmd.ExecuteNonQuery();
        }
        public void delete(int maloai)
        {
            SqlCommand cmd = new SqlCommand("LOAIHANG_DELETE", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@MALOAI", maloai);
            cmd.ExecuteNonQuery();
        }
        public LoaiHangColection Get(String where, int pageIndex, int pageSize, string orderBy, string orderDirection, out int totalRecords)
        {
            SqlCommand cm = new SqlCommand("LOAIHANG_GET", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@WHERE", where);
            cm.Parameters.AddWithValue("@PageIndex", pageIndex);
            cm.Parameters.AddWithValue("@PAGESIZE", pageSize);
            cm.Parameters.AddWithValue("@ORDERBY", orderBy);
            cm.Parameters.AddWithValue("@ORDERDIRECTION", orderDirection);

            //cm.Parameters .Add (new SqlParameter ("@TOTALRECORD",DbType.Int32)).Direction=ParameterDirection.Output 
            cm.Parameters.Add(new SqlParameter("@TOTALRECORDs", DbType.Int32)).Direction = ParameterDirection.Output;
            SqlDataReader dr = cm.ExecuteReader();
           LoaiHangColection LHCollection = new LoaiHangColection();
            while (dr.Read())
            {
                LoaiHang_DTO loaihang = new LoaiHang_DTO();
                loaihang.MaLoai = int.Parse(dr.GetValue(0).ToString());
                loaihang.TenLoai = dr.GetValue(1).ToString();
                LHCollection.Add(loaihang);


            }
            dr.Close();
            totalRecords = int.Parse(cm.Parameters["@TOTALRECORDs"].Value.ToString());
            return LHCollection;


        }

    }
}
